﻿using System;
using System.Linq;
using CourseManager.Model.Data;
using CourseManager.Model.Util;
using Ext.Net;

namespace CourseManager.View.Contents.Admin
{
	public partial class TeacherManageContent : System.Web.UI.Page
	{
		protected void Page_Load(object sender, EventArgs e)
		{
			if(!IsPostBack)
			{
				DBEntity ent = new DBEntity();
				var source = from teacher in ent.Tab_Teacher
							 from user in ent.Tab_User
							 where teacher.teacherId.Equals(user.userId)
				             select new
				                    	{
											teacherId = teacher.teacherId,
											name = teacher.name,
											sex = teacher.sex,
											dept = teacher.dept,
											password = user.password
				                    	};
				TeacherStore.DataSource = source;
				TeacherStore.DataBind();
			}
		}

		[DirectMethod]
		public void ShowUpdateWindow(string id, string name, string sex, string dept)
		{
			txtUpdateId.Text = id;
			txtUpdateName.Text = name;
			txtUpdateDept.Text = dept;
			cbUpdateSex.Text = sex;
			UpdateWindow.Show();
		}

		[DirectMethod]
		public void DeleteTeacher(string id)
		{
			TeacherDAO.Remove(id);
			Response.Redirect(Request.RawUrl);
		}

		protected void BtnAddOkClick(object sender, DirectEventArgs e)
		{
			try
			{
				TeacherDAO.Add(txtAddId.Text, txtAddName.Text, 
					txtAddDept.Text, cbAddSex.Text, txtAddId.Text);
				Response.Redirect(Request.RawUrl);
			} 
			catch(Exception ex)
			{
				ExtNet.Msg.Alert("错误", "添加失败，可能原因为ID重复");
			}
		}

		protected void BtnUpdateOkClick(object sender, DirectEventArgs e)
		{
			var ent = new DBEntity();
			var teacher = (from t in ent.Tab_Teacher
			               where t.teacherId.Equals(txtUpdateId.Text)
			               select t).FirstOrDefault();
			teacher.name = txtUpdateName.Text;
			teacher.sex = cbUpdateSex.Text;
			teacher.dept = txtUpdateDept.Text;
			ent.SaveChanges();
			Response.Redirect(Request.RawUrl);
		}
		
		[DirectMethod]
		public void DoResetPassword(string id)
		{
			UserDAO.ResetPassword(id);
		}

		protected void BtnSearchClick(object sender, DirectEventArgs e)
		{
			var keyword = txtKeyword.Text.Trim();
			if(keyword.Length == 0)
			{
				TeacherStore.DataSource = TeacherDAO.FindAll();
			}
			else
			{
				DBEntity ent = new DBEntity();
				var source = from teacher in ent.Tab_Teacher
							 from user in ent.Tab_User
							 where teacher.teacherId.Equals(user.userId)
								 && (teacher.teacherId.Contains(keyword)
								 || teacher.name.Contains(keyword)
								 || teacher.dept.Contains(keyword))
							 select new
							 {
								 teacherId = teacher.teacherId,
								 name = teacher.name,
								 sex = teacher.sex,
								 dept = teacher.dept,
								 password = user.password
							 };
				TeacherStore.DataSource = source;
			}
			pagingBar.SetPageIndex(1);
			TeacherStore.DataBind();
		}
	}
}